import { ParseAuth } from "@/utils/auth.js";
import redisClient from "~/utils/redis";

const isMoblie = (event) => {
    const userAgent = getHeader(event, "User-Agent");
    return /iPhone|iPad|iPod|Android/i.test(userAgent);
};

const getPlatform = (event) => {
    return isMoblie(event) ? "m" : "p";
};

const getToken = (event) => {
    const cookies = parseCookies(event);
    return cookies["ykj_token"];
};

export default defineEventHandler(async (event) => {
    const token = getToken(event);
    const query = await getQuery(event);
    let redirect = query["redirect"];
    let url = redirect.split("?");
    if (url.length > 1) {
        let search = "";
        const querys = url[1].split("&");
        querys.forEach((item, index) => {
            search += item.replace(/(.+)=(.+)/, function (_, $1, $2) {
                return `${$1}=${encodeURIComponent($2)}`;
            });
            if (index < querys.length - 1) search += "&";
        });
        redirect = url[0] + "?" + search;
    }
    const GoToLoginPage = async () => {
        await sendRedirect(event, "/login.html?redirect=" + redirect, 302);
    };
    if (token) {
        const userInfo = ParseAuth(token);
        if (userInfo && userInfo.id) {
            const saveToken = await redisClient.getVal(
                `token-${getPlatform(event)}-${userInfo.id}`
            );
            if (saveToken == token) {
                if (redirect) {
                    await sendRedirect(
                        event,
                        redirect +
                        `${redirect.includes("?") ? "&" : "?"}ticket=` +
                        token,
                        302
                    );
                }
                return "ok";
            }
        }
    }
    await GoToLoginPage();
    return "ok";
});
